import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        socketTast: null,
		id:null,
    },
    mutations: {
		
    }, 
    actions: {
        websocketInit ({ state, dispatch },id) {
			state.id = id
			//更改链接状态
            state.socketTast = uni.connectSocket({				
                url:"ws://health.cpzsyun.com/websocket/"+state.id,
                success: (e) => {
                   console.log('连接成功！'+e.errMsg)
                },
                fail: e => {
                    console.log('连接失败' + JSON.stringify(e))
                }
            })
            state.socketTast.onOpen(() => dispatch('websocketOnOpen'))
            state.socketTast.onClose(e => dispatch('websocketOnClose'))
            state.socketTast.onError(e => dispatch('websocketOnError'))
        },
        websocketOnOpen ({ state,dispatch }) {
			// console.log('聊天链接正常')
        },
        websocketOnClose ({ state, dispatch }) {
              dispatch('websocketInit',state.id)
        },
        websocketOnError ({ commit, dispatch }) {
			uni.showToast({
			  icon: 'none',
			  position: 'top',
			  title: '服务器错误！'
			});
        },
        websocketClose ({ state }) {
            if (!state.socketTast) return
            state.socketTast.close({
                success (res) {
                    console.log('关闭成功', res)
                },
                fail (err) {
                    console.log('关闭失败', err)
                }
            })
        },
    }

})

export default store